let db = require('../conf/db')
const jwtUtil = require('../public/utils/jwt')
let dayjs = require('dayjs')
let jwt = new jwtUtil()


const getUserList = async(req, res) => {
    let sql = 'SELECT u.loginName,u.userName,s.dict_key role,u.avatar,u.company,u.address,u.sex,u.birthday,u.telPhone,u.email FROM `mdm`.`user` u left join sys_dict s on u.role = s.id'
    let data = req.body
    sql += ' WHERE 1=1 '

    if (data.loginName || data.role || data.userName) {
        if (data.loginName) {
            sql += ' and u.loginName like "%' + data.loginName + '%"'
        }
        if (data.role) {
            sql += ' and s.id = "' + data.role + '"'
        }
        if (data.userName) {
            sql += ' and u.userName like "%' + data.userName + '%"'
        }
    }
    sql += ' and u.id >= (select id from user order by id limit '+ (data.listQuery.page-1)*data.listQuery.limit +', 1)  limit  ' +data.listQuery.limit

    db.query(sql, [], function(results, fields) {
        // db.query('SELECT count(id) count FROM mdm.user', [], function(result, fields) {
            // 以json的形式返回
       res.send({ code: 20000, data: {items:results,total:results.length} })
    //    })


    })
}
const getOperator = async(req, res) => {
    let sql = 'SELECT * FROM `mdm`.`user` where role = "431"'
    db.query(sql, [], function(results, fields) {
        // 以json的形式返回
        res.send({ code: 20000, data: results })


    })
}
const getAllUser = async(req, res) => {
    let sql = 'SELECT loginName value,userName label FROM `mdm`.`user` where 1=1'
    db.query(sql, [], function(results, fields) {
        // 以json的形式返回
        res.send({ code: 20000, data: results })


    })
}
const login = async(req, res) => {
    db.query('SELECT * FROM `mdm`.`user` WHERE `loginName` = "' + req.body.loginName + '" AND `password` = "' + req.body.password + '"', [], function(results, fields) {

        if (results.length > 0) {
            let token = jwt.generateToken(req.body)

            db.query('UPDATE `mdm`.`user` SET `isvalid` = 1 WHERE `loginName` = "' + req.body.loginName + '"')
                // 以json的形式返回
            res.send({ code: 20000, data: token })
        } else {
            // 以json的形式返回
            res.send({ code: 20001, data: '', message: '用户名不存在或密码错误！' })
        }


    })
}
const loginOut = async(req, res) => {
    let data = jwt.verifyToken(req.headers['x-token'])

    db.query('UPDATE `mdm`.`user` SET `isvalid` = 0  WHERE `loginName` = "' + data.loginName + '"', [], function(results, fields) {
        // 以json的形式返回
        res.send({ code: 20000, data: '退出成功' })



    })
}
const queryUserInfo = async(req, res) => {

    let datas = jwt.verifyToken(req.headers['x-token'])


    // sql查询user表
    db.query('SELECT u.loginName,u.userName,s.dict_key role,u.avatar,u.company,u.address,u.sex,u.birthday,u.telPhone,u.email FROM user u  left join sys_dict s on u.role=s.id WHERE u.loginName = "' + datas.data.loginName + '"', [], function(results, fields) {
        let birthdayYear = new Date(results[0].birthday).getFullYear()
        results[0].birthday = results[0].birthday ? dayjs(results[0].birthday).format('YYYY-MM-DD HH:mm:ss') : ''
        results[0].age = results[0].birthday ? new Date().getFullYear() - birthdayYear : ""
        results[0].avatar+='?'+new Date().getTime()
        // 以json的形式返回
        res.json({ code: 20000, data: results })
    })
}
const updateUserMessage = async(req, res) => {
        let datas = jwt.verifyToken(req.headers['x-token'])
        let query = req.body
        let sql = 'UPDATE `mdm`.`user` SET '

        for (const key in query) {
            if (query[key]) {
                if (key == 'age'||key == 'role') {
                    continue
                }
                sql += key + '="' + query[key] + '",'
            }
        }
        sql = sql.substring(0, sql.length - 1)
        sql += ' WHERE `loginName` = "' + datas.data.loginName + '"'
            // sql查询user表
        db.query(sql, [], function(results, fields) {
            // 以json的形式返回
            res.json({ code: 20000, data: results })
        })
    }
    //编辑别的用户信息
const editUserMessage = async(req, res) => {

    let query = req.body
    let sql = 'UPDATE `mdm`.`user` SET '

    for (const key in query) {
        if (query[key]) {
            if (key == 'age' || key == 'createDate') {
                continue
            }
            if(key=='role'&&!(!isNaN(parseFloat(query[key])) && isFinite(query[key]))){
                continue
            }
            sql += key + '="' + query[key] + '",'
        }
    }
    sql = sql.substring(0, sql.length - 1)
    sql += ' WHERE `loginName` = "' + query.loginName + '"'
        // sql查询user表
    db.query(sql, [], function(results, fields) {
        // 以json的形式返回
        res.json({ code: 20000, data: results })
    })
}
const delUser = async(req, res) => {

    let query = req.body
    let sql = 'DELETE FROM `mdm`.`user`  '

    sql += ' WHERE `loginName` = "' + query.loginName + '"'
        // sql查询user表
    db.query(sql, [], function(results, fields) {
        // 以json的形式返回
        res.json({ code: 20000, data: results })
    })
}
const updatePassword = async(req, res) => {
    let datas = jwt.verifyToken(req.headers['x-token'])
    let query = req.body
    db.query('SELECT password from  `mdm`.`user` WHERE `loginName` ="' + datas.data.loginName + '"', [], function(results, fields) {

            if (query.oldPassword == results[0].password) {
                db.query('UPDATE `mdm`.`user` SET `password` = "' + query.newPassword + '" WHERE `loginName` ="' + datas.data.loginName + '"', [], function(results, fields) {
                    // 以json的形式返回
                    res.json({ code: 20000, data: results, message: '密码修改成功,请重新登陆' })
                })
            } else {
                // 以json的形式返回
                res.json({ code: 20001, data: '', message: '密码验证失败,请稍后重试' })
            }

        })
        // sql查询user表

}
const registerUser = async(req, res) => {
    let data = req.body
        // sql查询user表
    db.query('INSERT INTO `mdm`.`user`( `loginName`,  `createDate`,  `role`, `avatar`, `password`) VALUES ( "' + data.loginName + '",  now() , (SELECT id FROM `sys_dict` WHERE dict_key = "editor"), "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif", "' + data.password + '")', [], function(results, fields) {
        // 以json的形式返回
        let token = jwt.generateToken(req.body)
        res.json({ code: 20000, data: token })
    })
}
module.exports = {
    login,
    loginOut,
    delUser,
    queryUserInfo,
    getAllUser,
    registerUser,
    getUserList,
    updateUserMessage,
    updatePassword,
    editUserMessage,
    getOperator
}